import 'dart:core';
import 'package:dio/dio.dart';
import '../config/Config.dart';
import '../model/ProductModel.dart';
import '../widget/LoadingWidget.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter/material.dart';

class ProductList extends StatefulWidget {
  Map? arguments;
  ProductList({Key? key, this.arguments}) : super(key: key);

  @override
  _ProductListState createState() => _ProductListState();
}

class _ProductListState extends State<ProductList> {
  //Scaffold key
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  //用于上拉分页  //listview的控制器
  ScrollController _scrollController = ScrollController();

  //分页
  int _page = 1;

  //每页有多少条数据
  int _pageSize = 8;

  //数据
  List _productList = [];

  /*
  排序:价格升序 sort=price_1 价格降序 sort=price_-1  销量升序 sort=salecount_1 销量降序 sort=salecount_-1
  */
  String _sort = "";

  //解决重复请求的问题
  bool flag = true;

  //是否有数据
  bool _hasMore = false;

  /*二级导航数据*/
  List _subHeaderList = [
    {
      "id": 1,
      "title": "综合",
      "fileds": "all",
      "sort":
          -1, //排序     升序：price_1     {price:1}        降序：price_-1   {price:-1}
    },
    {"id": 2, "title": "销量", "fileds": 'salecount', "sort": -1},
    {"id": 3, "title": "价格", "fileds": 'price', "sort": -1},
    {"id": 4, "title": "筛选"}
  ];

  //二级导航选中判断
  int _selectHeaderId = 1;

  @override
  void initState() {
    super.initState();

    print(widget.arguments!['cid']);

    _scrollController.addListener(() {
      //_scrollController.position.pixels //获取滚动条滚动的高度
      //_scrollController.position.maxScrollExtent  //获取页面高度
      // print(_scrollController.position.pixels);
      // print(_scrollController.position.maxScrollExtent - 20);
      if (_scrollController.position.pixels >
          _scrollController.position.maxScrollExtent - 20) {
        if (this.flag && this._hasMore) {
          _getProductListData();
        }
      }
    });
  }

  //获取商品列表的数据
  _getProductListData() async {
    setState(() {
      this.flag = false;
    });

    var api =
        '${Config.domain}api/plist?cid=${widget.arguments!["cid"]}&page=${this._page}&pageSize=${this._pageSize}';
    print(api);
    var result = await Dio().get(api);

    var productList = ProductModel.fromJson(result.data);

    print(productList.result!.length);

    if (productList.result!.length < this._pageSize) {
      setState(() {
        this._productList.addAll(productList.result!);
        this._hasMore = false;
        this.flag = true;
      });
    } else {
      setState(() {
        this._productList.addAll(productList.result!);
        this._page++;
        this.flag = true;
      });
    }
  }

  //显示加载中的圈圈
  Widget _showMore(index) {
    if (this._hasMore) {
      //模拟网络数据
      return (index == 9) ? LoadingWidget() : Text('');
    } else {
      return (index == 9) ? Text("--我是有底线的--") : Text('');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        title: Text('商品列表'),
        actions: [Text('')],
      ),
      endDrawer: Drawer(
        child: Container(
          child: Text('实现筛选功能'),
        ),
      ),
      body: Stack(children: [
        _subHeaderWidget(),
        _productListWidget(),
      ]),
    );
  }

//筛选导航
  Widget _subHeaderWidget() {
    return Positioned(
      width: 750.w,
      height: 80.h,
      top: 0,
      child: Container(
        // color: Colors.red,
        decoration: BoxDecoration(
          border: Border(
            bottom: BorderSide(
              width: 1,
              color: Color.fromRGBO(233, 233, 233, 0.9),
            ),
          ),
        ),
        child: Row(
          children: this._subHeaderList.map((e) {
            return Expanded(
              flex: 1,
              child: InkWell(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Container(
                      // color: Colors.yellow,
                      alignment: Alignment.center,
                      height: 80.h,
                      // width: double.infinity,
                      child: Text(
                        '${e['title']}',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                            color: (_selectHeaderId == e['id'])
                                ? Colors.red
                                : Colors.black54),
                      ),
                    ),
                    _showIcon(e['id']),
                  ],
                ),
                onTap: () {
                  _subHeaderChange(e['id']);
                },
              ),
            );
          }).toList(),
        ),
      ),
    );
  }

  //显示header 右侧Icon
  Widget _showIcon(id) {
    if (id == 2 || id == 3) {
      if (this._subHeaderList[id - 1]['sort'] == 1) {
        return Icon(Icons.arrow_drop_down);
      } else {
        return Icon(Icons.arrow_drop_up);
      }
    }
    return Text('');
  }

  //4个筛选按钮改变的时候触发
  _subHeaderChange(id) {
    if (id == 4) {
      _scaffoldKey.currentState?.openEndDrawer();
      setState(() {
        this._selectHeaderId = id;
      });
    } else {
      setState(() {
        this._selectHeaderId = id;
        this._sort =
            "${this._subHeaderList[id - 1]["fileds"]}_${this._subHeaderList[id - 1]["sort"]}";

        //重置分页
        this._page = 1;
        //重置数据
        this._productList = [];
        //改变sort排序
        this._subHeaderList[id - 1]['sort'] =
            this._subHeaderList[id - 1]['sort'] * -1;
        //回到顶部
        _scrollController.jumpTo(0);
        //重置_hasMore
        this._hasMore = true;
        //重新请求
        this._getProductListData();
      });
    }
  }

//商品列表
  Widget _productListWidget() {
    if (this._productList.length == 0) {
      return Container(
        margin: EdgeInsets.only(top: 80.h),
        padding: EdgeInsets.only(top: 10, left: 10, right: 10),
        child: ListView.builder(
          controller: _scrollController,
          itemCount: 10,
          itemBuilder: ((context, index) {
            //每一个元素
            return Column(
              children: [
                Row(
                  children: [
                    Container(
                      width: 180.w,
                      height: 180.h,
                      child: Image.network(
                        'https://www.itying.com/images/flutter/list2.jpg',
                        fit: BoxFit.cover,
                      ),
                    ),
                    Expanded(
                      flex: 1,
                      child: Container(
                        height: 180.h,
                        margin: EdgeInsets.only(left: 10),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              '戴尔(DELL)灵越3670 英特尔酷睿i5 高性能 台式电脑整机(九代i5-9400 8G 256G)',
                              maxLines: 2,
                              overflow: TextOverflow.ellipsis,
                            ),
                            Row(
                              children: [
                                Container(
                                  height: 36.h,
                                  margin: EdgeInsets.only(right: 10),
                                  padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                                  //注意 如果Container里面加上decoration属性，这个时候color属性必须得放在BoxDecoration
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(10),
                                    color: Color.fromRGBO(230, 230, 230, 0.9),
                                  ),
                                  child: Text('4g'),
                                ),
                                Container(
                                  height: 36.h,
                                  margin: EdgeInsets.only(right: 10),
                                  padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                                  //注意 如果Container里面加上decoration属性，这个时候color属性必须得放在BoxDecoration
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(10),
                                    color: Color.fromRGBO(230, 230, 230, 0.9),
                                  ),
                                  child: Text('126'),
                                ),
                                Container(
                                  height: 36.h,
                                  margin: EdgeInsets.only(right: 10),
                                  padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                                  //注意 如果Container里面加上decoration属性，这个时候color属性必须得放在BoxDecoration
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(10),
                                    color: Color.fromRGBO(230, 230, 230, 0.9),
                                  ),
                                  child: Text('独立显卡'),
                                ),
                              ],
                            ),
                            Text(
                              '¥990',
                              style: TextStyle(color: Colors.red, fontSize: 16),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
                Divider(
                  height: 20,
                ),
                _showMore(index),
              ],
            );
          }),
        ),
      );
    } else {
      //加载中
      return LoadingWidget();
    }
  }
}
